/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: uds_transport.c
 *
 * Purpose: implementation implementation unix domain socket transport(dialer and listener) ops for cbus
 *
 * Developer:
 *   wen.gu , 2022-02-16
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#if defined(_MSC_VER)
#include "uds_transport.h"
#include <time.h>
#include <process.h>

#include "cbus/core/cbus_worker.h"
#include "cbus/core/cbus_thread.h"

#include "cbus/core/cbus_log.h"
/******************************************************************************
 **    MACROS
 ******************************************************************************/

/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/

typedef struct _uds_dialer
{
    socket_t socket_;
    cbus_worker_t worker_;
    void* opaque;
    cbus_dialer_receive_handler on_receive;
}uds_dialer_t;


/******************************************************************************
 **    inner FUNCTION DEFINITIONS
 ******************************************************************************/

static GErrc dialer_create_socket(uds_dialer_t* dialer, const GSTR url)
{
    dialer->socket_ = socket(AF_UNIX, SOCK_STREAM, 0);

    if (dialer->socket_ < 0)
    {
        LOGE("create uds socket instance failed(%ld)\n", WSAGetLastError());
        return G_ErrInsufficientResources;
    } 

    struct sockaddr_un client_addr;
    memset(&client_addr, 0, sizeof(client_addr));            /* fill socket address structure with our address */
    client_addr.sun_family = AF_UNIX;
    time_t timeTotal = time(NULL);
    struct tm* ptm = localtime(&timeTotal);
    snprintf(client_addr.sun_path, sizeof(client_addr.sun_path), "%s_client_%d_%d-%d-%d-%d.%d.%d_%p", 
        url, _getpid(), ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, dialer);

    LOGI("client addr:%s, len:%zd\n", client_addr.sun_path, sizeof(struct sockaddr_un));

    int32_t ret = bind(dialer->socket_, (struct sockaddr*) & client_addr, sizeof(struct sockaddr_un));
    if (ret < 0)
    {
        LOGE("bind client socket:%s, failed:%ld\n", client_addr.sun_path, WSAGetLastError());
        closesocket(dialer->socket_);
        dialer->socket_ = INVALID_SOCKET;
        return G_ErrUndefined;
    }

    // set the socket in non-blocking
    unsigned long mode = 1;
    int result = ioctlsocket(dialer->socket_, FIONBIO, &mode);
    if (result != NO_ERROR)
    {
        LOGE("ioctlsocket failed with error: %ld\n", result);
        closesocket(dialer->socket_);
        dialer->socket_ = INVALID_SOCKET;
        return G_ErrUndefined;
    }

    return G_OK;
}

static GErrc dialer_do_connect(uds_dialer_t* dialer, const GSTR url)
{
    struct sockaddr_un server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sun_family = AF_UNIX;
    snprintf(server_addr.sun_path, sizeof(server_addr.sun_path), "%s", url);
    LOGI("client addr:%s, len:%zd\n", server_addr.sun_path, sizeof(struct sockaddr_un));
    int res = connect(dialer->socket_, (struct sockaddr*) & server_addr, sizeof(struct sockaddr_un));

    if (res == SOCKET_ERROR)
    {
        if (WSAGetLastError() != WSAEWOULDBLOCK)
        {
            LOGE("[%s.%d]===>: connect to(%s) failed(err: %ld)\n", __FUNCTION__, __LINE__, server_addr.sun_path, WSAGetLastError());
            return G_ErrUndefined;            
        }
    }
    

    fd_set Write, Err;
    FD_ZERO(&Write);
    FD_ZERO(&Err);
    FD_SET(dialer->socket_, &Write);
    FD_SET(dialer->socket_, &Err);

    TIMEVAL timeval = { 0 };
    timeval.tv_sec = 2; /** default 2 second ,todo refine me?? */
    timeval.tv_usec = 0;

    // check if the socket is ready
    int32_t ret = select(0, NULL, &Write, &Err, &timeval);
    
    if (ret > 0)
    {        
        return G_OK;
    }
    else if (ret == 0)
    {
        /** todo something */  
        return G_ErrTimeout;
    }
    else
    {
        LOGE("connect failed with error: %ld\n", WSAGetLastError());
        return G_ErrUndefined;
    }    
}

static void dialer_receive_worker(cbus_worker_t thd_worker, void* opaque)
{
    uds_dialer_t* dialer = (uds_dialer_t*)opaque;
    uint8_t receive_buf[2048];

    while (cbus_worker_running(thd_worker))
    {
        if (dialer->socket_ != INVALID_SOCKET)
        {
            int ret_len = recv(dialer->socket_, (char*)receive_buf, 2048, 0);

            if (ret_len > 0)
            {
                if (dialer->on_receive)
                {
                    dialer->on_receive(dialer->opaque, receive_buf, ret_len);
                }
            }
            else
            {
                if (errno != EINTR)
                { /**disconnected between client and service */
                    closesocket(dialer->socket_);
                    dialer->socket_ = INVALID_SOCKET;  /** todo refine me?? */
                }
            }
        }
        else
        {
            cbus_thread_sleep(40); // todo refine me?? 
         //   doReconnect(); /** will max block 2 second */
        }         

    }    
}

/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/
/**
 * @brief create and initialize a dialer instance
 * @param handle [out] a instance of dialer
 * @return GErrc, success: G_OK, else error code.
 * 
*/
GErrc uds_dialer_initialize(GPHD* handle)
{
    if (!handle)
    {
        return G_ErrBadParameter;
    }

    uds_dialer_t* dialer = (uds_dialer_t*)malloc(sizeof(uds_dialer_t));

    if (dialer)
    {
        memset(dialer, 0, sizeof(*dialer));
        GErrc ret = cbus_worker_create(&(dialer->worker_), "dialer_receive", dialer_receive_worker, dialer);

        if (G_OK != ret)
        {
            free(dialer);
            return ret;
        }

        *handle = (GPHD)dialer;
        return G_OK;
    }

    return G_ErrInsufficientResources;
}

/**
 * @brief destroy a dialer instance
 * @param handle [in] a instance of dialer
 * @return GErrc, success: G_OK, else error code.
 * 
 */
GErrc uds_dialer_finish(GPHD handle)
{
    if (!handle)
    {
        return G_ErrBadParameter;
    }

    uds_dialer_t* dialer = (uds_dialer_t*)handle;
    //todo something 

    if (dialer->worker_)
    {
        cbus_worker_join(dialer->worker_);
    }

    if (dialer->socket_)
    {
        closesocket(dialer->socket_);
        dialer->socket_ = INVALID_SOCKET;
    }

    free(handle);
    return G_OK;
}

/**
 * @brief connect to a listener(service)
 * @param handle [in] a instance of dialer
 * @param url [in] the url adress of listener(service)
 * @return GErrc, success: G_OK, else error code.
 * 
 */
GErrc uds_dialer_connect(GPHD handle, const GSTR url)
{
    if (!handle || !url || (strlen(url) <= UDS_TRANSPORT_URL_PREFIX_LEN)) /** url len must > UDS_TRANSPORT_URL_PREFIX_LEN */
    {
        return G_ErrBadParameter;
    }

    uds_dialer_t* dialer = (uds_dialer_t*)handle;

    GErrc ret = dialer_create_socket(dialer, url + UDS_TRANSPORT_URL_PREFIX_LEN);

    if (ret == G_OK)
    {
        ret = dialer_do_connect(dialer, url + UDS_TRANSPORT_URL_PREFIX_LEN);
        if (G_OK == ret)
        {
            ret = cbus_worker_start(dialer->worker_);
        }
    }

    return ret;
}

/**
 * @brief distconnect from listener(service)
 * @param handle [in] a instance of dialer
 * @return GErrc, success: G_OK, else error code.
 * 
 */ 
GErrc uds_dialer_disconnect(GPHD handle)
{
    if (!handle)
    {
        return G_ErrBadParameter;
    }

    uds_dialer_t* dialer = (uds_dialer_t*)handle;

    if (dialer->worker_)
    {
        cbus_worker_pause(dialer->worker_);
    }

    if (dialer->socket_ != INVALID_SOCKET)
    {
        closesocket(dialer->socket_);
        dialer->socket_ = INVALID_SOCKET;
    }

    return G_OK;
}

/**
 * @brief send data to remote side
 * @param handle [in] a instance handle for data transport
 * @param buf [in] data buffer
 * @param len [in] data length
 * @return G_OK: success, else: failed @see GErrc 
 * 
 */
GErrc uds_dialer_send(GPHD handle, GBUF buf, GU32 len)
{
    if (!handle)
    {
        return G_ErrBadParameter;
    }

    uds_dialer_t* dialer = (uds_dialer_t*)handle;  

    if (dialer->socket_ == INVALID_SOCKET)
    {
        return G_ErrInvalidStatus;
    }

    while (len > 0)
    {
        int32_t ret_len = send(dialer->socket_, (char*)buf, len, 0);
        if (ret_len > 0)
        {
            len -= ret_len;
            buf += ret_len;
        }
        else if (ret_len == 0)
        {
            return G_ErrDisconnected;
        }
        else
        {
            if (errno != EINTR)
            {
                return G_ErrDisconnected;
            }
            /** todo something */
        }
    } 

    return G_OK;
}

/**
 * @brief set a receiver handler as callback to receive data from remote side
 * @param handle [in] a instance handler for data transport
 * @param opaque [in] a oapque handle of user for Receiver handler
 * @param on_receive [in] a callback for receive data from remote side
 * @return success:G_OK, else: error code @see GErrc
 * 
 */
GErrc uds_dialer_set_receiver(GPHD handle, cbus_dialer_receive_handler on_receive, void* opaque)
{
    if (!handle)
    {
        return G_ErrBadParameter;
    }

    uds_dialer_t* dialer = (uds_dialer_t*)handle;  
    dialer->on_receive = on_receive;
    dialer->opaque = opaque;
    return G_OK;
}

#endif